// 用于处理复杂数据类型v-model（父 v-model => 子 v-model（子这里通过useEasyVModel转换父传过来的props对应数据） => 孙 ），且要保持单项数据流的情况
import { computed } from 'vue'
export function useEasyVModel<P extends object, K extends keyof P, Name extends string>(
  props: P,
  key: K,
  emit: (name: Name, ...args: any[]) => void
) {
  return computed({
    get() {
      let o: any = null
      o = easyProxy(JSON.parse(JSON.stringify(props[key])), () => {
        emit(`update:${key as string}` as Name, JSON.parse(JSON.stringify({ ...o })))
      })
      return o
    },
    set(nV) {
      emit(`update:${key as string}` as Name, nV)
    }
  })
}
function easyProxy(obj: any, cb: Function) {
  return new Proxy(obj, {
    get(target, key): any {
      let val = Reflect.get(target, key)
      if (val !== null && typeof val === 'object') return easyProxy(val, cb) // 递归
      return val
    },
    set(target, key, valuse): boolean {
      const result = Reflect.set(target, key, valuse)
      cb() // 更新
      return result
    }
  })
}
